package com.heatup.apt.api.service.impl;

import com.heatup.apt.api.service.CourseSignService;
import com.heatup.apt.api.service.OrderService;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.dao.CourseSignMapper;
import com.heatup.apt.common.dao.OrderDetailMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.user.UserSignMapper;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.course.CourseSign;
import com.heatup.apt.model.order.OrderDetail;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserSign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.heatup.apt.api.service.UserSignService;
import com.baomidou.framework.service.impl.SuperServiceImpl;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * UserSign 表数据服务层接口实现类
 *
 */
@Service
public class UserSignServiceImpl extends SuperServiceImpl<UserSignMapper, UserSign> implements UserSignService {


    Logger logger = LoggerFactory.getLogger(UserSignServiceImpl.class);

    @Resource
    private UserSignMapper userSignMapper;
    @Resource
    private CourseSignService courseSignService;
    @Resource
    private OrderService orderService;
    @Resource
    private CourseSignMapper courseSignMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;


    /**
     *@Author: timo
     *@Date: 2018/4/4 11:17
     *@Description:
     * 用户的签到
     * 1.私教的签到 如果总的签到节数和总的课时数量相等的话就表示 该课程和订单已经完成
     * 2.团课的签到 一旦有一个人签到成功 就表示该日程已经签到完成并且用户的订单都是已完成状态
     * 3.训练营的签到  因为训练营已经分成多个日程 只有每个日程都有人签到的时候才算订单的完成
     * 4.体测体验 已签到就算该订单完成
     *
     */
    @Override
    public ApiResultModel saveUserSign(UserInfo userInfo, Integer courseSignId, Integer courseId, Integer orderId) {
        ApiResultModel apiResultModel = new ApiResultModel();
        Map<String,Object> resultMap = new HashMap<>();

        // 校验
        apiResultModel = checkUserSign(userInfo, courseSignId, courseId, orderId, apiResultModel);
        if(apiResultModel.getRet() != ApiResultModel.RET_SUCCESS){
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            return apiResultModel;
        }

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("courseSignId",courseSignId);
        paramMap.put("courseId",courseId);
        paramMap.put("orderId",orderId);
        paramMap.put("userId",userInfo.getId());


        OrderInfo orderInfo = courseSignMapper.queryOrderInfoBy(paramMap);
        if( orderInfo == null) {
            resultMap.put("signStatus",2);
            apiResultModel.setData(resultMap);
            apiResultModel.setRet(apiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("您没有预约该课程");
            return apiResultModel;
        }



        int addCount = userSignMapper.insertUserSign(courseSignId,orderId,userInfo.getId());

        if(addCount > 0){
            // 用户签到成功
            // 教练端修改签到的状态
            // 需要查出该用户的订单人数
            OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());
            courseSignService.userSignUpdateCourseSign(courseSignId,orderDetail.getPersonCount());
            updateCourseStatus(userInfo, courseSignId, courseId, orderInfo);
            apiResultModel.setRet(apiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("签到成功");
            resultMap.put("signStatus",1);
            apiResultModel.setData(resultMap);
            return apiResultModel;
        }
        resultMap.put("signStatus",2);
        apiResultModel.setData(resultMap);
        apiResultModel.setRet(apiResultModel.RET_SUCCESS);
        apiResultModel.setMsg("您没有预约该课程");
        return apiResultModel;
    }

    /**
     *@Author: timo
     *@Date: 2018/4/4 16:18
     *@Description:
     * 校验用户签到
     *
     */
    public ApiResultModel checkUserSign(UserInfo userInfo, Integer courseSignId, Integer courseId, Integer orderId, ApiResultModel resultModel){
        Map<String,Object> resultMap = new HashMap<>();
        // 判断是否重复签到
        if (checkUserRepeatSign(courseSignId, userInfo.getId())){
            resultModel.setRet(ApiResultModel.RET_ERROR);
            resultMap.put("signStatus",3);
            resultModel.setMsg("已签到");
            resultModel.setData(resultMap);
            return resultModel;
        }

        CourseSign courseSign = courseSignMapper.selectById(courseSignId);

        // 签到的该日程不存在
        if(courseSign == null){
            resultModel.setRet(ApiResultModel.RET_ERROR);
            resultModel.setMsg("签到的该课程不存在");
            return resultModel;
        }

        // 未到签到时间
//        if(!courseSign.getStartTime().before(new Date())){
//            resultModel.setRet(ApiResultModel.RET_ERROR);
//            resultModel.setMsg("该课程未到签到时间");
//            return resultModel;
//        }

        resultModel.setRet(ApiResultModel.RET_SUCCESS);
        return resultModel;

    }

    // 校验是否有重复签到
    public boolean checkUserRepeatSign(Integer courseSignId, Integer userId){

//        UserSign userSign = new UserSign();
//        userSign.setCourseSignId(courseSignId);
//        userSign.setUserId(userId);
//        userSign = userSignMapper.selectOne(userSign);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("courseSignId",courseSignId);
        resultMap.put("userId",userId);
        List<UserSign> userSignList = userSignMapper.queryUserSignBy(resultMap);
        if(userSignList.size() > 0) return Boolean.TRUE;
        return Boolean.FALSE;
    }


    public void updateCourseStatus(UserInfo userInfo, Integer courseSignId, Integer courseId, OrderInfo orderInfo){

        // 私教
        if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.pt.getIndex()) {
            updatePtCourse(courseSignId, userInfo.getId(), courseId, orderInfo);

        } else if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.fun_camp.getIndex()) {
//            updateCampCourse(userInfo, courseId, orderInfo);

        } else if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.team_course.getIndex()) {
//            updateTeamCourse(orderInfo);

        } else if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.physical_examination.getIndex()
                || orderInfo.getOrderType().intValue() == OrderContants.OrderType.secret_experience.getIndex()) {
            // 体测体验课程
            updatePlpeOrPlecCourse(orderInfo);

        }
    }

    /**
     *@Author: timo
     *@Date: 2018/4/4 11:09
     *@Description:
     *
     *
     */
    public void updatePtCourse(Integer courseSignId, Integer userId, Integer courseId, OrderInfo orderInfo){
        // 先查询该课程是不是已经全部销课完了
        Integer isLastClass = courseSignMapper.checkIsLastClass(courseId);

        // 表示最后一节课
        // 修改课程状态
        // 修改订单状态
        if(isLastClass != null && isLastClass == 1){
            orderInfo.setOrderStatus(OrderContants.OrderStatus.FINISH.getStatus());
            orderInfo.setUpdatedTime(new Date());
            orderInfo.setUpdatedBy(orderInfo.getUserId());
            orderService.updateById(orderInfo);
        }

    }

    public void updateTeamCourse(OrderInfo orderInfo){
        // 订单状态置为已完成
        orderInfo.setOrderStatus(OrderContants.OrderStatus.FINISH.getStatus());
        orderInfo.setUpdatedTime(new Date());
        orderInfo.setUpdatedBy(orderInfo.getUserId());
        orderService.updateById(orderInfo);

    }

    public void  updateCampCourse(UserInfo userInfo, Integer courseId, OrderInfo orderInfo){
        Integer isLastClass = courseSignMapper.checkIsLastClass(courseId);
        if(isLastClass != null && isLastClass == 1){
            orderInfo.setOrderStatus(OrderContants.OrderStatus.FINISH.getStatus());
            orderInfo.setUpdatedTime(new Date());
            orderInfo.setUpdatedBy(userInfo.getId());
            orderService.updateById(orderInfo);
        }

    }

    public void updatePlpeOrPlecCourse(OrderInfo orderInfo){
        orderInfo.setOrderStatus(OrderContants.OrderStatus.FINISH.getStatus());
        orderInfo.setUpdatedTime(new Date());
        orderInfo.setUpdatedBy(orderInfo.getUserId());
        orderService.updateById(orderInfo);
    }


}